import * as vscode from 'vscode';

export class MetaManager {
    private static readonly FILE = 'meta.json';

    private static async read(dotUri: vscode.Uri): Promise<Record<string, any>> {
        const uri = vscode.Uri.joinPath(dotUri, MetaManager.FILE);
        try {
            const buf = await vscode.workspace.fs.readFile(uri);
            return JSON.parse(Buffer.from(buf).toString('utf-8'));
        } catch {
            return {};
        }
    }

    private static async write(dotUri: vscode.Uri, data: Record<string, any>) {
        const uri = vscode.Uri.joinPath(dotUri, MetaManager.FILE);
        const txt = JSON.stringify(data, null, 2);
        await vscode.workspace.fs.writeFile(uri, Buffer.from(txt, 'utf-8'));
    }

    static async set(dotUri: vscode.Uri, metaData: Map<string, any>) {
        const meta = await MetaManager.read(dotUri);
        Object.assign(meta, Object.fromEntries(metaData));
        await MetaManager.write(dotUri, meta);
    }
}
